/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: JsonLevelChangeInterceptor.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;

import java.io.IOException;

import io.bhex.baselib.network.response.OrginResponse;
import io.bhex.baselib.network.interceptor.Interceptor;
import io.bhex.baselib.utils.DebugLog;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 对于response进行层级关系的修改
 */
public class JsonLevelChangeInterceptor implements Interceptor {

    /**
     * 把data这个节点摘出来，平铺
     *
     * @param responseData
     * @return
     */
    public String intercept(String responseData) {
//        return responseData;

        if (TextUtils.isEmpty(responseData))
            return responseData;

        OrginResponse response = null;
        try {
            response = JSON.parseObject(responseData, OrginResponse.class);
        } catch (Exception e) {
            DebugLog.e(e);
            return responseData;
        }

        if (response == null)
            return responseData;

        //查看data字符串的情况
        String dataInfo = response.getData();

        //data不是一个object，不用平铺了
        if (TextUtils.isEmpty(dataInfo) || !dataInfo.trim().startsWith("{"))
            return responseData;
        else {
            //data里存放源数据，后续有可能用到（当data作为map时，会有这种问题）
            StringBuffer builder = new StringBuffer();
            builder.append(responseData)
                    .deleteCharAt(builder.length() - 1)
                    .append(",")
                    .append(dataInfo.substring(1, dataInfo.length()));

            return builder.toString();
        }
    }

    @Override
    public Request intercept(Request request, okhttp3.Interceptor.Chain chain) {
        return request;
    }

    @Override
    public Response intercept(Response response, okhttp3.Interceptor.Chain chain) throws IOException {
        if (response == null || !response.isSuccessful())
            return response;

//        String newResponse = intercept(response.body().string());
        String newResponse = interceptData(response.body().string());

        if (response.body() != null)
            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), newResponse))
                    .build();
        else
            return response;
    }


    /**
     * 拦截返回数据 如果返回的Json为数组，改成JsonObject key为array
     * @param data
     * @return
     */
    private String interceptData(String data) {
        if (!TextUtils.isEmpty(data)) {
            if (data.startsWith("[")&&data.endsWith("]")) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("{\"array\":");
                stringBuffer.append(data);
                stringBuffer.append("}");
                return stringBuffer.toString();
            }
        }
        return data;
    }
}
